<?php
Yii::import('zii.widgets.grid.CGridView');

class GridView extends CGridView {

    public $dropDowns;
    public $dropDownCssClass = 'grid-dropdown-selector';

    /**
     * Renders the sorter.
     */
    public function renderItems() {

        $this->dataProvider->debugSql();

        $this->dropDown();

        parent::renderItems();
    }//end function

    public function dropDown() {

        if ($this->dataProvider->itemCount <= 0 || !$this->enableSorting || $this->dropDowns === null)
            return;

        $route = $this->controller->route;

        function dropDownRedirect($params) {
            $name = $id = $params['type'];
            $htmlOptions = $params['htmlOptions'];
            $replacement = '__value__';

            $script = '$("#' . $id . '").change(function(){'
                    . '$(location).attr("href", "' . $params['url'] . '".replace("' . $replacement . '", $(this).val()));'
                    . '});';
            Yii::app()->clientScript->registerScript(__FUNCTION__ . $id, $script);

            if (!isset($htmlOptions['id']))
                $htmlOptions['id'] = $id;
            $script = 'window.location = "' . $params['url'] . '".replace("' . $replacement . '", $(this).val());';
            if (!isset($htmlOptions['onChange']))
                $htmlOptions['onChange'] = $script;
            return CHtml::dropDownList($name, $params['select'], $params['data'], $htmlOptions);
        }//end function

        echo CHtml::openTag('div', array('class' => $this->dropDownCssClass));

        foreach ($this->dropDowns as $type => $config) {

            if (!isset($config['cssClass']))
                $config['cssClass'] = $type;
            if (!isset($config['label']))
                $config['label'] = 'Select a ' . $type;
            if (!isset($config['items']))
                $config['items'] = array();
            if (!isset($config['dropDownVar']))
                $config['dropDownVar'] = $type;
            if (!isset($config['default']))
                $config['default'] = null;

            //if(Yii::app()->request->getParam($config['dropDownVar']) == $config['default']) unset($_REQUEST[$config['dropDownVar']]);

            echo CHtml::openTag('div', array('class' => $config['cssClass']));
            echo CHtml::label($config['label'], $type);

            echo dropDownRedirect(array(
                'type' => $type,
                'data' => $config['items'],
                'url' => Yii::app()->createUrl($route, array_merge($_REQUEST, array($config['dropDownVar'] => '__value__'))),
                'select' => Yii::app()->request->getParam($config['dropDownVar'], $config['default']),
                'htmlOptions' => array(
                    'id' => $type,
                ),
            ));

            echo CHtml::closeTag('div');
        }//end foreach

        echo CHtml::closeTag('div');
    }//end function
}//end class